/**
 * @Title: UpdateSignFlagSyncLogic.java
 * @Package: com.jason.fingerprint.logic
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月24日 上午10:03:51
 * @Version: V1.0
 */
package com.jason.fingerprint.logic;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.google.gson.GsonBuilder;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.AppGlobal;
import com.jason.fingerprint.beans.LeaveOutBean;
import com.jason.fingerprint.beans.LeaveResp;
import com.jason.fingerprint.beans.ui.ImageOrAudioBean;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.configs.HttpConfig;
import com.jason.fingerprint.utils.CodecUtils;
import org.kymjs.aframe.http.HttpCallBack;
import org.kymjs.aframe.http.KJFileParams;
import org.kymjs.aframe.http.KJHttp;
import org.kymjs.aframe.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: UpdateSignFlagSyncLogic
 * @Description: 上传签到信息
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月24日 上午10:03:51
 */
public class UpdateSignFlagSyncLogic extends Logic {

	private static final String TAG = "UpdateSignFlagSyncLogic";

	private Handler mHandler;
	private boolean mIsCallBack = false;// 是否有回调，此需要Handle,默认不回调
	private Message mMessage;
	private List<LeaveOutBean> mLeaveOutBeans = new ArrayList<LeaveOutBean>();
	private int mSize = 0;
	private int mCount = 0;

	public UpdateSignFlagSyncLogic() {

	}

	public UpdateSignFlagSyncLogic(AppContext appContext, Handler handler) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
	}

	public UpdateSignFlagSyncLogic(AppContext appContext, Handler handler,
			boolean isCallBack) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
		this.mIsCallBack = isCallBack;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jason.fingerprint.logic.Logic#execute()
	 */
	@Override
	public void execute() {
		// TODO Auto-generated method stub
		mSize = 0;
		mCount = 0;
		mLeaveOutBeans = mKjdb.findAllByWhere(LeaveOutBean.class, "state = 1");
		if (mLeaveOutBeans != null && !mLeaveOutBeans.isEmpty()) {
			mSize = mLeaveOutBeans.size();
			httpPost();
		} else {
			mMessage.what = UIHelper.LEAVEOUT_UPLOAD_SUCCESS;
			send();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jason.fingerprint.logic.Logic#send()
	 */
	@Override
	public void send() {
		// TODO Auto-generated method stub
		if (mIsCallBack) {
			mHandler.sendMessage(mMessage);
			mMessage = new Message();
		}
	}

	private void httpPost() {
		if (mCount >= mSize) {
			mMessage.what = UIHelper.LEAVEOUT_UPLOAD_SUCCESS;
			send();
			return;
		}
		final LeaveOutBean bean = mLeaveOutBeans.get(mCount);
		if (bean != null) {
			String signType = bean.getSignType();
			if (!StringUtils.isEmpty(signType)) {
				String url = HttpConfig.POST_URL_EGRESSLEAVE_UPDATESIGNFLAG;
				mParams = new KJFileParams();
				mParams.put(AppGlobal.HTTP_PARAM_IMEI, mImei);
				mParams.put("signType", signType);
				mParams.put("id", bean.getId());
				mParams.put("signFlag", bean.getSignFlag());
				if (signType.equals("3")) {
					// 销假
					mParams.put("rymcId", bean.getRymcid());
				}
				mParams.put("time", bean.getTime());
				mParams.put("registrationType", String.valueOf(bean.getRegistrationType()));
				Log.i(TAG,"****** http mParams *******" + mParams.getParamString());
				KJHttp kjHttp = new KJHttp();
				kjHttp.post(url, mParams, new HttpCallBack() {

					@Override
					public void onSuccess(Object arg0) {
						Log.i(TAG, "----->arg0:" + arg0.toString());
						String result = null;
						try {
							result = CodecUtils.base64Decode(arg0.toString());
						} catch (Exception e) {
							mMessage.what = UIHelper.LEAVEOUT_UPLOAD_FAIL;
							send();
							return;
						}
						Log.i(TAG, "----->Result:" + result);
						LeaveResp baseBeanean = new GsonBuilder().create().fromJson(
								result, LeaveResp.class);
						if (baseBeanean != null && baseBeanean.isSuccess()) {
							if (mCount >= mSize) {
								//循环结束
								String errorMessage = baseBeanean.getRespMsg();
								mMessage.what = UIHelper.LEAVEOUT_UPLOAD_SUCCESS;
								mMessage.obj = errorMessage;
								send();
							}else {
								//修改数据库，更新数据
								List<String> values = baseBeanean.getValues();
								if (values != null && !values.isEmpty()){
									String id = values.get(0);
									bean.setState(2);
									bean.setLeaveId(id);
									mKjdb.update(bean, "leaveoutId = " + bean.getLeaveoutId());

									//修改对应的图片资源
									StringBuilder where = new StringBuilder();
									where.append("parentId  = '");
									where.append(bean.getId());
									where.append("'");
									where.append(" and ");
									where.append("serviceId   = ");
									where.append(UploadToTempSyncLogic.SERVICE.SERVICE_LEAVE_OUT);
									where.append(" and ");
									where.append("signType   = '");
									where.append(bean.getSignType());
									where.append("'");

									List<ImageOrAudioBean> imageOrAudioBeans = mKjdb.findAllByWhere(ImageOrAudioBean.class, where.toString());
									if (imageOrAudioBeans != null && !imageOrAudioBeans.isEmpty()){
										for (ImageOrAudioBean imageOrAudioBean : imageOrAudioBeans){
											imageOrAudioBean.setParentId(id);
											mKjdb.update(imageOrAudioBean);
										}
									}
								}
								mCount ++;
								httpPost();
							}
						} else {
							// 请假签到失败
							mMessage.what = UIHelper.LEAVEOUT_UPLOAD_FAIL;
							send();
						}
					}

					@Override
					public void onLoading(long arg0, long arg1) {
						Log.i(TAG, "----->Result:arg0:" + arg0 + ",arg1:"
								+ arg1);
					}

					@Override
					public void onFailure(Throwable arg0, int arg1, String arg2) {
						Log.i(TAG, "----->Result:arg1:" + arg1 + ",arg2:"
								+ arg2);
						mMessage.what = UIHelper.LEAVEOUT_UPLOAD_FAIL;
						send();
					}
				});
			}
		}
	}

	/* (non-Javadoc)
	 * @see com.jason.fingerprint.logic.Logic#destory()
	 */
	@Override
	public void destory() {
		// TODO Auto-generated method stub
		
	}

}
